#include "log.hpp"
#include "Protocol.hpp"
volatile bool quit = false;
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "Usage\n\t" << argv[0] << " ip port" << endl;
        exit(USAGE_ERR);
    }
    string ip = argv[1];
    uint16_t port = atoi(argv[2]);

    // 1.创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        logMessage(FATAL, "sockfd :%s", strerror(errno));
        exit(SOCKET_ERR);
    }
    // 2.发起连接请求
    // 2.1填充服务器基本信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    inet_aton(ip.c_str(), &server.sin_addr);
    // 2.2发起请求
    if (connect(sockfd, (const struct sockaddr *)&server, sizeof server) != 0)
    {
        logMessage(FATAL, "connect :%s", strerror(errno));
        exit(CONN_ERR);
    }
    logMessage(DEBUG, "connect :%s,sockfd:%d ", strerror(errno), sockfd);

    string message;
    while (!quit)
    {
        message.clear();
        cout << "请输入你的信息：";
        // fflush(stdout);
        getline(cin, message);
        if (strcasecmp("quit", message.c_str()) == 0)
        {
            quit = true;
            continue;
        }

        clearSpace(message); // 去掉空格
        Request req;
        if (!makeRequest(message, &req))
        {
            // cout << "message:" << message << endl;
            cout << "makeRequest error" << endl;
            continue;
        }
        string package; // 将要发送的包
        req.serialize(&package);
        cout << "package:" << package << endl;
        encode(&package);

        ssize_t s = write(sockfd, package.c_str(), package.size());
        if (s > 0) // 读取服务器响应
        {
            message.resize(1024);
            ssize_t t = read(sockfd, (void *)message.c_str(), 1024);
            if (t > 0)
            {
                message[t] = '\0';
                Response resp;
                uint32_t len = 0;
                decode(message, &len);
                if (len > 0)
                {
                    if (resp.deserialize(message))
                        cout << "[exitCode:" << resp.exitCode_ << "]" << resp.result_ << endl;
                    else
                        cerr << "response deserialize error" << endl;
                }
                else
                    cerr << "server echo# wrong data format!" << endl;
            }
        }
        else if (s <= 0)
        {
            break;
        }
    }
    close(sockfd);
    return 0;
}